import { useEffect, useState } from 'react';

function UseEffectCleanupDemo() {
  const [show, setShow] = useState(true);

  return (
    <div>
      <button onClick={() => setShow(!show)}>
        {show ? '卸载计时器' : '挂载计时器'}
      </button>
      {show && <Timer />}
    </div>
  );
}

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);
    // 清理副作用：组件卸载时清除定时器
    return () => {
      clearInterval(interval);
      console.log('定时器已清除');
    };
  }, []);

  return <div>计时：{seconds} 秒</div>;
}

export default UseEffectCleanupDemo;
